package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO orderSubmitDTO) {
        // 1. 业务异常
        AddressBook addressBook = addressBookMapper.getById(orderSubmitDTO.getAddressBookId());
        if (addressBook == null) {//地址簿为空
            throw new IllegalArgumentException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        //查询购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(userId);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new IllegalArgumentException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 2. 订单表插入数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDTO, orders);

        orders.setUserId(userId);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getAddress());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        orderMapper.insert(orders);

        // 3. 订单明细表插入数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        if (!orderDetailList.isEmpty()) {
            orderMapper.insertOrderDetail(orderDetailList);
        }

        // 4. 购物车表数据删除
        shoppingCartMapper.cleanByUserId(userId);

        // 5. 返回VO
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();

        return orderSubmitVO;
    }

    /**
     * 历史订单查询
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);
        for (OrderVO orderVO : page) {
            orderVO.setOrderDetailList(orderMapper.getOrderDetailByOrderId(orderVO.getId()));
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 条件查询
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.conditionSearch(ordersPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 订单详情
     */
    @Override
    public OrderVO getById(Long id) {
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderMapper.getOrderDetailByOrderId(id));
        return orderVO;
    }

    /**
     * 订单统计
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(orderMapper.countByStatus(Orders.TO_BE_CONFIRMED))
                .confirmed(orderMapper.countByStatus(Orders.CONFIRMED))
                .deliveryInProgress(orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS))
                .build();
        return orderStatisticsVO;
    }

    /**
     * 取消订单
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        orderMapper.cancel(ordersCancelDTO, LocalDateTime.now());
    }

    /**
     * 订单拒绝
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.rejection(ordersRejectionDTO);
    }

    /**
     * 订单确认
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.confirm(ordersConfirmDTO);
    }

    /**
     * 订单派送
     */
    @Override
    public void delivery(Long id) {
        orderMapper.delivery(id);
    }

    /**
     * 订单完成
     */
    @Override
    public void complete(Long id) {
        orderMapper.complete(id);
    }

    /**
     * 支付
     */
    @Override
    public OrderPaymentVO pay(OrdersPaymentDTO ordersPaymentDTO) {
        orderMapper.pay(ordersPaymentDTO);
        //通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type", 1);//1表示来单提醒2表示客户催单
        map.put("orderId", ordersPaymentDTO.getOrderNumber());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        return OrderPaymentVO.builder()
                .nonceStr("abc123def456")
                .packageStr("prepay_id=wx1234567890")
                .paySign("signature1234567890")
                .timeStamp(String.valueOf(System.currentTimeMillis() / 1000))
                .signType("MD5")
                .build();
    }

    /**
     * 催单
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new RuntimeException("订单不存在");
        }
        //通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type", 2);//1表示来单提醒2表示客户催单
        map.put("orderId", orders.getNumber());
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 再来一单
     */
    @Override
    public void repetition(Long id) {
        Orders orders = orderMapper.getById(id);
        String number =String.valueOf(System.currentTimeMillis());
        orders.setNumber(number);
        orders.setStatus(2);
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.insert(orders);
        // 订单明细表插入数据
        List<OrderDetail> orderDetailList = orderMapper.getOrderDetailByOrderId(id);
        for (OrderDetail orderDetail : orderDetailList){
            orderDetail.setOrderId(orderMapper.getIdByNumber(number));
        }
        if (!orderDetailList.isEmpty()) {
            orderMapper.insertOrderDetail(orderDetailList);
        }
        //通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type", 1);//1表示来单提醒2表示客户催单
        map.put("orderId", orders.getNumber());
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
